package com.dark;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by tengxue on 16-6-6.
 */
public class CuratorFrameworkTest {
    private  static  CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("172.26.50.83:2181")
            .sessionTimeoutMs(5000)
            .connectionTimeoutMs(3000)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3))
            .build();
    private static final String BASE_PATH="/zk-dark-example";
    public static void main(String[] args)throws Exception{

        String helloPath2=BASE_PATH+"/wwww";
        String helloValue2="www.baidu.com";
        String childHelloPath=BASE_PATH+"/wwww/node1";
        String childHelloValue="node1";
        String childHelloPath2=BASE_PATH+"/wwww/node2";
        String childHelloValue2="node2";
        Map<String,String> childs=new HashMap<String,String>();
        childs.put(childHelloPath,childHelloValue);
        childs.put(childHelloPath2,childHelloValue2);


        client.start();

//        String path=createNode("/global_lock", "/global_lock");



//        byte[] data=client.getData().forPath(path);
//        System.out.println("the data is :" + new String(data));
//        List<String> result=createChildNode(childs);
//        List<String> childPath=client.getChildren().forPath(helloPath2);
//        System.out.println("the childPath is :"+childPath);

        //分布式锁
        CountDownLatch latch = new CountDownLatch(5);
        System.out.println("客户端启动。。。。");
        ExecutorService exec = Executors.newCachedThreadPool();

        for (int i = 0; i < 5; i++) {
            exec.submit(new MyLock("client" + i, client, latch));
        }

        exec.shutdown();
        latch.await();
        System.out.println("所有任务执行完毕");

        client.close();

        System.out.println("客户端关闭。。。。");


        client.close();
    }
    static class MyLock implements Runnable {

        private String name;

        private CuratorFramework client;

        private CountDownLatch latch;

        public MyLock(String name, CuratorFramework client, CountDownLatch latch) {
            this.name = name;
            this.client = client;
            this.latch = latch;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void run() {
            InterProcessMutex lock = new InterProcessMutex(client,
                    "/test_group");
            try {
                if (lock.acquire(120, TimeUnit.SECONDS)) {
                    try {
                        // do some work inside of the critical section here
                        System.out.println("----------" + this.name
                                + "获得资源----------");
                        System.out.println("----------" + this.name
                                + "正在处理资源----------");
                        Thread.sleep(10 * 1000);
                        System.out.println("----------" + this.name
                                + "资源使用完毕----------");
                        latch.countDown();
                    } finally {
                        lock.release();
                        System.out.println("----------" + this.name
                                + "释放----------");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    private static String createNode(String helloPath, String helloValue) throws Exception {
        String  result=helloPath;
        //创建一个节点
        Stat stat=client.checkExists().forPath(helloPath);
        //没有这个节点
        if (null==stat){
            result=client.create().withMode(CreateMode.PERSISTENT).forPath(helloPath, helloValue.getBytes());
            System.out.println("the result is :"+result);
        }

        return result;
    }

    private static List<String> createChildNode(Map<String,String> nodes) throws Exception {
        List<String> paths=new ArrayList<String>();
        String path;
        for (Map.Entry<String,String> entry:nodes.entrySet()){
            path=createNode(entry.getKey(),entry.getValue());
            paths.add(path);

        }
        return paths;
    }
}
